const postcss = require('postcss')
const Px2rem = require('px2rem')
const path = require('path')

module.exports = postcss.plugin('postcss-px2rem-filter', (options) => {
    return (css, result) => {
        const filePath = css.source.input.file

        const include = options.include
        let isInclude = false
        if (include) {
            if (Array.isArray(include)) {
                const p = include.find(item => {
                    return filePath.includes(path.normalize(item))
                })
                if (p) {
                    isInclude = true
                }
            } else if (typeof (include) === 'string') {
                if (filePath.includes(path.normalize(include))) {
                    isInclude = true
                } else {
                    isInclude = false
                }
            } else {
                isInclude = false
            }
        }

        if (filePath.includes(`node_modules`)) {
            result.root = css
            return
        }

        if (isInclude) {
            // console.log(`路径 ${filePath} 使用px2rem`)
            const opt = JSON.parse(JSON.stringify(options))
            const oldCssText = css.toString()
            const px2remIns = new Px2rem(opt)
            const newCssText = px2remIns.generateRem(oldCssText)
            result.root = postcss.parse(newCssText)
        } else {
            result.root = css
        }
    }
})
